package com.azt.back.action.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azt.api.pojo.Function;
import com.azt.api.service.FuncService;
import com.azt.back.util.ContextUtils;
import com.azt.model.AjaxJson;
import com.azt.model.easy.EasyTree;

import net.sf.json.JSONArray;

@Controller
public class FuncAction {
	
	
	@Autowired
	private FuncService manager;
	

	
	@RequestMapping(value = "function/v_function.do", method = RequestMethod.GET)
	public String functions(HttpServletRequest request,
			HttpServletResponse response, ModelMap model){
		return "admin/function/func_list";
	}
		
	/** 
	 * 进入页面后调用
	 * @author  张栋
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping(value="function/ajax_tree.do")
	@ResponseBody
	public List<EasyTree> ajaxForTree(){
		return manager.getFuncTree();
	}
	
	
	@RequestMapping(value="function/ajax_funTree.do")
	@ResponseBody
	public JSONArray ajaxForFunTree(HttpServletRequest request){
		String funcs = request.getParameter("funcs");
		JSONArray treeJsonArray = manager.getFunETreeJsonArray(funcs);
		return treeJsonArray;
	}
	
	
	
	
	@RequestMapping(value="function/ajax_add.do")
	@ResponseBody
	public AjaxJson ajaxAdd(Function func,HttpServletRequest request,
			HttpServletResponse response, ModelMap model){
		AjaxJson aj = new AjaxJson();
		Integer id = func.getId();
		if(id!=null&&!"".equals(id)){
			Function oldfunc = manager.getFunctionById(id);
			oldfunc.setName(func.getName());
			oldfunc.setSortnum(func.getSortnum());
			oldfunc.setUri(func.getUri());
			manager.saveOrUpdate(oldfunc);
		}else{
			manager.saveOrUpdate(func);
		}
		ContextUtils.has_changed=true;
		return aj;
	}
	
	@RequestMapping(value="function/ajax_del.do")
	@ResponseBody
	public AjaxJson ajaxDel(Function func,HttpServletRequest request,
			HttpServletResponse response, ModelMap model){
		AjaxJson aj = new AjaxJson();
		Integer id = func.getId();
		if(id!=null&&!"".equals(id)){
			manager.delFunction(id);
		}
		return aj;
	}
	@RequestMapping(value="function/addIcon.do")
	@ResponseBody
	public AjaxJson addIcon(Integer id,String icon){

		AjaxJson j = new AjaxJson();
		Function entity = manager.getFunctionById(id);
		if(StringUtils.isBlank(icon)){
			entity.setIcon(null);	
		}else{
			entity.setIcon(icon);
		}
		manager.saveOrUpdate(entity);
		return j;
	}
}
